﻿using Microsoft.Extensions.DependencyInjection;
using Modules.CheckInCount.StatisticModels;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;

namespace Modules.CheckInCount.Repositories;

[UseDI(ServiceLifetime.Scoped)]
public class CheckInStatisticRepository
{
    private readonly CheckinDbContext dbContext;
    private readonly IApplicationContext applicationContext;

    public CheckInStatisticRepository(CheckinDbContext dbContext, IApplicationContext applicationContext)
    {
        this.dbContext = dbContext;
        this.applicationContext = applicationContext;
    }


    /// <summary>
    /// 项目考勤统计
    /// </summary>
    /// <param name="stageType"></param>
    /// <param name="projectId"></param>
    /// <param name="date"></param>
    /// <returns></returns>
    public ProjectCheckinStatisticInfo GetProjectCheckinStatisticInfo(CountStageType stageType, int projectId, DateTime date)
    {
        if (stageType == CountStageType.Day)
        {
            Sql sql = Sql.Builder.Select()
                .Append($"(SELECT statistics_count FROM project_checkin_perday WHERE object_id=@0 AND year=@1 AND month=@2 AND day=@3) AS CheckinCount,", projectId, date.Year, date.Month, date.Day)
                .Append($"(SELECT statistics_count FROM project_persontime_perday WHERE object_id=@0 AND year=@1 AND month=@2 AND day=@3) AS CheckinPersonCount", projectId, date.Year, date.Month, date.Day);
            return dbContext.First<ProjectCheckinStatisticInfo>(sql);
        }
        if (stageType == CountStageType.Month)
        {
            Sql sql = Sql.Builder.Select()
              .Append($"(SELECT statistics_count FROM project_checkin_permonth WHERE object_id=@0  AND year=@1 AND month=@2 ) AS CheckinCount,", projectId, date.Year, date.Month)
              .Append($"(SELECT statistics_count FROM project_persontime_permonth WHERE object_id=@0 AND year=@1 AND month=@2) AS CheckinPersonCount", projectId, date.Year, date.Month);
            return dbContext.First<ProjectCheckinStatisticInfo>(sql);
        }
        throw new NotImplementedException($"未实现的统计阶段：{stageType}");
    }

    /// <summary>
    /// 获取项目指定月份考勤天数
    /// </summary>
    /// <param name="projectId"></param>
    /// <param name="year"></param>
    /// <param name="month"></param>
    /// <returns></returns>
    public int GetProjectCheckinDays(int projectId, int year, int month)
    {
        Sql sql = Sql.Builder
            .Select("COUNT(0)")
            .From("project_persontime_perday")
            .Where("object_id=@0 AND year=@1 AND month=@2", projectId, year, month);
        return dbContext.ExecuteScalar<int>(sql);
    }


}